package com.itheima.auth.controller.v1;

import com.itheima.auth.service.WechatOAuth2Service;
import com.itheima.model.admin.dtos.WechatBindDto;
import com.itheima.model.common.dtos.ResponseResult;
import com.itheima.utils.common.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 微信OAuth2登录控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/wechat")
@Api(tags = "微信扫码登录接口")
public class WechatOAuthController {
    
    @Autowired
    private WechatOAuth2Service wechatOAuth2Service;
    
    /**
     * 生成微信扫码登录授权URL
     */
    @GetMapping("/auth-url")
    @ApiOperation("获取微信扫码登录授权URL")
    public ResponseResult getAuthUrl(
            @ApiParam("状态参数(可选)") @RequestParam(required = false) String state) {
        return wechatOAuth2Service.generateAuthUrl(state);
    }
    
    /**
     * 微信授权回调处理
     */
    @GetMapping("/callback")
    @ApiOperation("微信授权回调接口")
    public ResponseResult callback(
            @ApiParam("授权码") @RequestParam String code,
            @ApiParam("状态参数") @RequestParam String state) {
        return wechatOAuth2Service.handleCallback(code, state);
    }
    
    /**
     * 绑定微信账号
     */
    @PostMapping("/bind")
    @ApiOperation("绑定微信账号")
    public ResponseResult bindWechat(@RequestBody WechatBindDto dto) {
        return wechatOAuth2Service.bindWechat(dto);
    }
    
    /**
     * 解绑微信账号
     */
    @DeleteMapping("/unbind")
    @ApiOperation("解绑微信账号")
    public ResponseResult unbindWechat(@RequestHeader("Authorization") String token) {
        // 从token中获取管理员ID
        String actualToken = token.replace("Bearer ", "");
        Integer adminId = JwtUtil.getUserId(actualToken);
        
        return wechatOAuth2Service.unbindWechat(adminId);
    }
}

